<template>
  <div class="xtx-city" ref="target">
    <div class="select" @click="toggle">
      <span v-if="placeholder" class="placeholder">{{ placeholder }}</span>
      <!-- 这是选择好的省市区数据 -->
      <span class="value">{{ fullLocation }}</span>
      <i class="iconfont icon-angle-down"></i>
    </div>
    <!-- 显示省市区 -->
    <div class="option" v-if="active">
      <div v-if="loading" class="loading"></div>
      <template v-else>
        <span class="ellipsis" @click="changeOption(item)" v-for="item in currList" :key="item.code">{{ item.name
        }}</span>
      </template>
    </div>
  </div>
</template>
<script>
import axios from 'axios'
import { ref, computed, reactive } from 'vue'
import { onClickOutside } from '@vueuse/core'
export default {
  name: 'XtxCity',
  props: {
    fullLocation: {
      type: String,
      default: ''
    },
    placeholder: {
      type: String,
      default: ''
    }
  },
  setup(props, { emit }) {
    // 加载中效果的控制变量
    const loading = ref(false)
    // 定义数据控制下拉的展开和收起
    const active = ref(false)
    // 定义方法来控制展开和收起
    const open = () => {
      active.value = true
      loading.value = true
      //  把要监听的省市区的数据设置为空对象
      for (const key in changeResult) {
        changeResult[key] = ''
      }
      // 获取数据
      getCityData().then(data => {
        cityData.value = data
        loading.value = false
      })
    }
    const close = () => {
      active.value = false
    }
    // 切换
    const toggle = () => {
      active.value ? close() : open()
    }
    // 点击其他位置隐藏
    const target = ref(null)// 目标dom
    onClickOutside(target, () => {
      close()
    })
    // 定义一个数据保存省市区数据
    const cityData = ref([])
    // 定义计算属性
    const currList = computed(() => {
      let currList = cityData.value
      // TODO 根据点击的省份城市获取对应的列表
      // 如果当前点击了省
      if (changeResult.provinceCode) {
        currList = currList.find(v => v.name === changeResult.provinceName).areaList
      }
      if (changeResult.cityCode) {
        currList = currList.find(v => v.name === changeResult.cityName).areaList
      }

      return currList
    })
    // 定义要监听的省市区数据
    const changeResult = reactive({
      provinceCode: '',
      provinceName: '',
      cityCode: '',
      cityName: '',
      countyCode: '',
      countyName: '',
      fullLocation: ''
    })
    // 点击城市数据选项，显示对应的数据
    const changeOption = (item) => {
      if (item.level === 0) {
        changeResult.provinceName = item.name
        changeResult.provinceCode = item.code
      }
      // 市
      if (item.level === 1) {
        changeResult.cityCode = item.code
        changeResult.cityName = item.name
      }
      // 区
      if (item.level === 2) {
        changeResult.countyCode = item.code
        changeResult.countyName = item.name
        // 关闭选择项
        close()
        // 把新选择的数据替换原来的默认选项
        changeResult.fullLocation = `${changeResult.provinceName} ${changeResult.cityName} ${changeResult.countyName}`
        // 把这个新的数据返回给父组件
        emit('change', changeResult)
      }
    }

    return { active, toggle, target, loading, currList, changeOption }
  }
}
// 获取城市数据
// 1. 数据在哪里？https://yjy-oss-files.oss-cn-zhangjiakou.aliyuncs.com/tuxian/area.json
// 2. 何时获取？打开城市列表的时候，做个内存中缓存
// 3. 怎么使用数据？定义计算属性，根据点击的省份城市展示
const getCityData = () => {
  // 这个位置可能有异常操作，封装成promise
  return new Promise((resolve, reject) => {
    if (window.cityData) {
      // 有缓存
      resolve(window.cityData)
    } else {
      // 无缓存
      const url = 'https://yjy-oss-files.oss-cn-zhangjiakou.aliyuncs.com/tuxian/area.json'
      axios.get(url).then(res => {
        // window.cityData = res.data
        resolve(res.data)
      })
    }
  })
}
</script>
<style scoped lang="less">
.xtx-city {
  display: inline-block;
  position: relative;
  z-index: 400;

  .select {
    border: 1px solid #e4e4e4;
    height: 30px;
    padding: 0 5px;
    line-height: 28px;
    cursor: pointer;

    &.active {
      background: #fff;
    }

    .placeholder {
      color: #999;
    }

    .value {
      color: #666;
      font-size: 12px;
    }

    i {
      font-size: 12px;
      margin-left: 5px;
    }
  }

  .option {
    width: 542px;
    border: 1px solid #e4e4e4;
    position: absolute;
    left: 0;
    top: 29px;
    background: #fff;
    min-height: 30px;
    line-height: 30px;
    display: flex;
    flex-wrap: wrap;
    padding: 10px;

    .loading {
      height: 290px;
      width: 100%;
      background: url(../../assets/images/loading.gif) no-repeat center;
    }

    >span {
      width: 130px;
      text-align: center;
      cursor: pointer;
      border-radius: 4px;
      padding: 0 3px;

      &:hover {
        background: #f5f5f5;
      }
    }
  }
}
</style>